package jp.co.jbuy.action.search;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilderFactory;

import jp.co.jbuy.action.BaseAction;
import jp.co.jbuy.common.ResourceManager;
import jp.co.jbuy.product.ProductDetail;
import jp.co.jbuy.product.ProductImage;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class SearchAction extends BaseAction {
	  public static final String PAGE_ID = "search";
	  public static final String PAGE_URL = "./jsp/search/searchResult.jsp";
	  private ArrayList<ProductDetail> productDetailList=new ArrayList<ProductDetail>();

	  public void action() throws Exception{
		  String searchParameter=req_.getParameter("search_keyword");
		  if(searchParameter!=null){
			  int searchTarget=getIntParameter("search_target");
			  if(searchTarget == 1){
				// Local DB.
				  
			  }
			  else if(searchTarget == 2){
				  setProductDetailListFromYahoo(searchParameter);
			  }
			  else{
				  
			  }
		      req_.setAttribute("productDetailList",productDetailList);
		      req_.setAttribute("searchKeyword",searchParameter);
		      req_.setAttribute("searchTarget",searchTarget);	      
		  }
	      forward(PAGE_URL);
	}
	  
	private void setProductDetailListFromYahoo(String searchParameter) throws Exception{
	  String reqUrl =createSearchYahooReqURL(ResourceManager.getYahooSearchReqUrl(),searchParameter);
	  // Web API にアクセスして結果をDOMで取得
      Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(reqUrl);
      NodeList nlist = doc.getElementsByTagName("Item");
      ProductDetail productDetail=null;
      for(int i = 0; i <nlist.getLength(); i++) { 
    	productDetail= new ProductDetail();
        NodeList resParam = nlist.item(i).getChildNodes();
        for(int j = 0; j <resParam.getLength(); j++) {   
        	Node node=resParam.item(j);
        	String nodeName=node.getNodeName();
        	if(nodeName.equals("AuctionID")) {
        		productDetail.setAuctionID(node.getFirstChild().getNodeValue());
        	}
        	else if(nodeName.equals("Title")) {
        		productDetail.setTitle(node.getFirstChild().getNodeValue());
        	}
        	else if(nodeName.equals("Image")) {
        		NamedNodeMap attributes = node.getAttributes();
        		Node widthNode = attributes.getNamedItem("width");
        		Node heightNode = attributes.getNamedItem("height");
        		ProductImage image=new ProductImage(Integer.valueOf(widthNode.getNodeValue()),Integer.valueOf(heightNode.getNodeValue()),
        				productDetail.getTitle(),node.getFirstChild().getNodeValue());
        		productDetail.setImage1(image);
            }
        	else if(nodeName.equals("CurrentPrice")) {
        		productDetail.setPrice(Double.valueOf(node.getFirstChild().getNodeValue()));
            }
        	else if(nodeName.equals("EndTime")) {
        		productDetail.setEndTime((new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")).parse(node.getFirstChild().getNodeValue()));
            }
            	
        }
        productDetailList.add(productDetail);
      }
	}
	  
    public static String createSearchYahooReqURL(String actionReqUrl,String strParameterValue) throws UnsupportedEncodingException{
    	actionReqUrl += "?appid=";         
    	actionReqUrl += URLEncoder.encode(ResourceManager.getYahooClientId(), "UTF-8") + "&"; // アプリケーションID("取得したID"は取得したアプリケーションID)
    	actionReqUrl += "query=";
    	actionReqUrl += URLEncoder.encode(strParameterValue, "UTF-8") + "&"; // 検索文字列
    	actionReqUrl += "format=";
    	actionReqUrl += URLEncoder.encode("html", "UTF-8"); // 検索文書型
	    
    	return actionReqUrl;
    	
    }
	  
  }
